package com.yogurt.edu.controller;


import com.yogurt.edu.client.VodClient;
import com.yogurt.edu.entity.Video;
import com.yogurt.edu.service.VideoService;
import com.yogurt.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author yogurt
 * @since 2020-07-10
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class VideoController {
    @Autowired
    private VideoService videoService;

    @Autowired
    private VodClient vodClient;

    //添加课时小节
    @PostMapping("/addVideo")
    public Result addVideo(@RequestBody Video video){
        boolean save = videoService.save(video);
        if (save){
            return Result.ok();
        }else {
            return Result.error();
        }
    }

    /*
        修改课时小节,分为两步
        ①:根据小节id查询小节,进行数据回显
        ②:修改小节
     */

    //根据小节id查询小节
    @GetMapping("/findVideoById/{videoId}")
    public Result findVideoById(@PathVariable String videoId){
        Video video = videoService.getById(videoId);
        if (video == null){
            return Result.error();
        }
        return Result.ok().data("video",video);
    }

    //修改小节
    @PutMapping("/updateVideo")
    public Result updateVideo(@RequestBody Video video){
        boolean flag = videoService.updateById(video);
        if (!flag){
            return Result.error();
        }
        return Result.ok();
    }

    //根据id删除小节(要把阿里云中的视频删除)
    @DeleteMapping("/deleteVideo/{videoId}")
    public Result deleteVideo(@PathVariable String videoId){
        //通过videoId查询出Video对象
        Video video = videoService.getById(videoId);
        //通过Video对象得到视频的id
        String videoSourceId = video.getVideoSourceId();

        if (!StringUtils.isEmpty(videoSourceId)){ //如果videoSourceId不为空则进行删除
            //远程调用方法进行删除
            vodClient.deleteVideo(videoSourceId);
        }
        boolean flag = videoService.removeById(videoId);
        if (!flag){
            return Result.error();
        }
        return Result.ok();
    }

}

